package com.qf.smsplatform.gateway.thread;

import com.qf.smsplatform.common.constants.RabbitMQConstants;
import com.qf.smsplatform.common.constants.ReportStateConstants;
import com.qf.smsplatform.common.constants.SourceType;
import com.qf.smsplatform.common.model.StandardReport;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.gateway.mq.DelayMessagePostProcessor;
import com.qf.smsplatform.gateway.mq.StatQueue;
import com.qf.smsplatform.gateway.netty4.entity.CmppDeliver;
import com.qf.smsplatform.gateway.netty4.entity.ReportMatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import static com.qf.smsplatform.gateway.config.RabbitConfig.QUEUE_DELAY_PER_MESSAGE_TTL_MSG_SMS_SEND;

public class SendReportThread implements Runnable {
    private final static Logger log = LoggerFactory.getLogger(SendReportThread.class);

    private AmqpTemplate rabbitTemplate;

    private String pushTopic;
    private String updateTopic;

    private StatQueue statqueue = StatQueue.getInstance();

    public SendReportThread(String pushTopic, String updateTopic, AmqpTemplate rabbitTemplate) {
        this.pushTopic = pushTopic;
        this.updateTopic = updateTopic;
        this.rabbitTemplate = rabbitTemplate;
    }

    @Autowired
    private AmqpAdmin amqpAdmin;

    @Override
    public void run() {
        while (true) {
            try {
                if (statqueue.size() > 0) {
                    log.info("stat queue size:{}", statqueue.size());
                    CmppDeliver deliver = (CmppDeliver) statqueue.remove();  // 从队列取出deliver对象
                    String str = deliver.getStat();             // 获取到了最终发送的状态
                    long msgid = deliver.getMsg_Id_DELIVRD();   // 最终的msgid运营商信息编号
                    ReportMatch reportMatch = ReportMatch.getInstance();
                    log.info("从REPORT MATCH中取值：{}", msgid);
                    StandardSubmit standardSubmit = (StandardSubmit) reportMatch.remove(msgid);  // 取出了submit对象
                    StandardReport report = new StandardReport();         // 创建了report对象（为了发送状态报告）
                    report.setSrcID(standardSubmit.getSrcSequenceId());
                    report.setMobile(standardSubmit.getDestMobile());

                    //校验短信是否成功发送
                    if (deliver.getResult() == 0) {  //判断result==0证明短信发送成功，或者Stat == DELIVRD 也代表短信发送成功
                        report.setState(ReportStateConstants.SUCCESS);
                        // TODO 发送消息到MQ，供监听模块获取消息进行Redis和数据库中费用操作
                        //封装submit中reportState  0成功  1等待   2失败
                        standardSubmit.setReportState(0);
                        //准备队列名称
                        String queueName = RabbitMQConstants.SMS_FEE_SEND_TOPIC;
                        //创建队列
                        amqpAdmin.declareQueue(QueueBuilder.durable(queueName).build());
                        //向MQ指定队列发送消息，供网关模块消费
                        rabbitTemplate.convertAndSend(queueName,standardSubmit);

                    } else {
                        report.setState(ReportStateConstants.FAIL);
                        report.setErrorCode(deliver.getStat());
                        // TODO 发送消息到MQ，供监听模块获取消息进行Redis费用操作
                        //封装submit中reportState  0成功  1等待   2失败
                        standardSubmit.setReportState(2);
                        //准备队列名称
                        String queueName = RabbitMQConstants.SMS_FEE_SEND_TOPIC;
                        //创建队列
                        amqpAdmin.declareQueue(QueueBuilder.durable(queueName).build());
                        //向MQ指定队列发送消息，供网关模块消费
                        rabbitTemplate.convertAndSend(queueName,standardSubmit);
                    }
                    //将sequenceId设置到report中，方便修改日志时，获取到文档id
                    report.setSequenceId(standardSubmit.getSequenceId());

                    report.setMsgId(String.valueOf(msgid));
                    report.setClientID(standardSubmit.getClientID());           // 在封装report对象
                    log.info("send report:{}", report);

                    //判断发送短信方式是否为HTTP
                    if (standardSubmit.getSource() == SourceType.HTTP) {
                        rabbitTemplate.convertAndSend(pushTopic, report);   // 发送状态报告
                    }
                    // 发送更新日志的消息
                    rabbitTemplate.convertAndSend(QUEUE_DELAY_PER_MESSAGE_TTL_MSG_SMS_SEND, report, new DelayMessagePostProcessor(10 * 1000));

                } else {
                    sleep(2000);
                }
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
                sleep(2000);
            }
        }
    }

    private void sleep(long time) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
    }
}
